//
//  QRCodeViewController.swift
//  weibo
//
//  Created by 陈经纬 on 16/7/21.
//  Copyright © 2016年 陈经纬. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {
    /// 底部按钮
    @IBOutlet weak var tabbarItems: UITabBar!
    /// 冲击波高度约束
    @IBOutlet weak var topLenth: NSLayoutConstraint!
    /// 容器视图高度
    @IBOutlet weak var containViewHeight: NSLayoutConstraint!
    //冲击波视图
    @IBOutlet weak var animationView: UIImageView!
    //显示结果
    @IBOutlet weak var textLB: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //1.设置默认选中
        tabbarItems.selectedItem = tabbarItems.items?.first
        tabbarItems.delegate = self

        //3.开始扫描二维码
        secanQRCode()
        
    }
    
    override func viewDidAppear(animated: Bool){
        super.viewWillAppear(animated)
        //2.设置动画方法
        setupAnimation()
    }
  /***********************************************/
    //MARK:内部实现方法
     //2.动画方法
    
    private func setupAnimation(){
        //一开始冲击波的高度是在扫码区域顶部
        self.topLenth.constant = -containViewHeight.constant
        self.view.layoutIfNeeded()
        
        //执行动画
        UIView.animateWithDuration(2, animations: {
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.topLenth.constant = self.containViewHeight.constant
            self.view.layoutIfNeeded()
        }) { (true) in
            
        }

    }
    
    
    
    
    //3.开始扫描二维码
    private func secanQRCode(){
        //1.判断输入能否添加到会话中
        if !session.canAddInput(input){
            return
        }
        //2.判断输出能否添加到会话中
        if !session.canAddOutput(output) {
            return
        }
        //3.添加输入和输出到会话中
        session.addInput(input)
        session.addOutput(output)
        //4.设置输出能够解析的数据类型
        //注意点:设置数据类型一定要在输出对象添加到会话之后才能设置
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        //5.设置监听输出解析到的数据
        
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        //6.添加预览图层
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        previewLayer.frame = view.bounds
        //7.开启扫描
        session.startRunning()
        
    }


    @IBAction func closeBtn(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /**打开相册*/
    @IBAction func photoBtn(sender: AnyObject) {
        // 打开相册
        // 1.判断是否能够打开相册
        /*
         case PhotoLibrary  相册
         case Camera 相机
         case SavedPhotosAlbum 图片库
         */
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
        {
            return
        }
        
        // 2.创建相册控制器
        let imagePickerVC = UIImagePickerController()
        
        imagePickerVC.delegate = self
        // 3.弹出相册控制器
        presentViewController(imagePickerVC, animated: true, completion: nil)
    }
    
    
    @IBAction func visitCardCilck(sender: AnyObject) {
        
//        let visitCard = QRVsitCardViewController()
////        let visitCardVC = visitCard.instantiateInitialViewController()
//        presentViewController(visitCard, animated: true, completion: nil)
        
    }
    
    
    
    /***************************************************/
    //MARK:懒加载
    
    
    /// 1. 创建输入对象
 
    private var input: AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        return try? AVCaptureDeviceInput(device:device)
    }()
    
    /// 2.创建会话
    private lazy var session: AVCaptureSession = AVCaptureSession()
    
    /// 3.创建输出对象
    private lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    ///4.创建预览图层----预览相机画面
    private lazy var previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
    /// 专门用于保存描边的图层
    private lazy var containerLayer: CALayer = CALayer()

}




// MARK: - AVCaptureMetadataOutputObjectsDelegate代理方法
extension QRCodeViewController:AVCaptureMetadataOutputObjectsDelegate{
    
    /**
     只要扫描到结果就会调用

     */
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!){
        
        //只要扫描到结果
        textLB.text = metadataObjects.last?.stringValue
        
        clearLayers()
        
        // 2.拿到扫描到的数据
        guard let metadata = metadataObjects.last as? AVMetadataObject else
        {
            return
        }
        // 通过预览图层将corners值转换为我们能识别的类型
        let objc = previewLayer.transformedMetadataObjectForMetadataObject(metadata)
        // 2.对扫描到的二维码进行描边
        drawLines(objc as! AVMetadataMachineReadableCodeObject)
    }
    
    /// 绘制描边
    private func drawLines(objc: AVMetadataMachineReadableCodeObject)
    {
        
        // 0.安全校验
        guard let array = objc.corners else
        {
            return
        }
        
        // 1.创建图层, 用于保存绘制的矩形
        let layer = CAShapeLayer()
        layer.lineWidth = 2
        layer.strokeColor = UIColor.greenColor().CGColor
        layer.fillColor = UIColor.clearColor().CGColor
        
        // 2.创建UIBezierPath, 绘制矩形
        let path = UIBezierPath()
        var point = CGPointZero
        var index = 0
        CGPointMakeWithDictionaryRepresentation((array[index++] as! CFDictionary), &point)
        
        // 2.1将起点移动到某一个点
        path.moveToPoint(point)
        
        // 2.2连接其它线段
        while index < array.count
        {
            CGPointMakeWithDictionaryRepresentation((array[index++] as! CFDictionary), &point)
            path.addLineToPoint(point)
        }
        // 2.3关闭路径
        path.closePath()
        
        layer.path = path.CGPath
        // 3.将用于保存矩形的图层添加到界面上
        containerLayer.addSublayer(layer)
    }
    
    /// 清空描边
    private func clearLayers()
    {
        guard let subLayers = containerLayer.sublayers else
        {
            return
        }
        for layer in subLayers
        {
            layer.removeFromSuperlayer()
        }

    }
}


// MARK: - UITabBarDelegate代理方法
extension QRCodeViewController:UITabBarDelegate{
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem){
        item.tag == 2 ? (containViewHeight.constant = 80) : (containViewHeight.constant = 200)
    view.layoutIfNeeded()
        
        animationView.layer.removeAllAnimations()
        
        setupAnimation()
    }
}


//MARK: - UIImagePickerControllerDelegate..代理方法
extension QRCodeViewController:UINavigationControllerDelegate, UIImagePickerControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
        
        // 1.取出选中的图片
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else{
            return
        }
        guard let ciImage = CIImage(image:image) else {
            return
        }
        // 2.从选中的图片中读取二维码数据
        // 2.1创建一个探测器
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyLow])
        // 2.2利用探测器探测数据
        let results = detector.featuresInImage(ciImage)
        // 2.3取出探测到的数据
        for result in results
        {
            JWLog((result as! CIQRCodeFeature).messageString)
        }
        
        // 注意: 如果实现了该方法, 当选中一张图片时系统就不会自动关闭相册控制器
        picker.dismissViewControllerAnimated(true, completion: nil)

    }
    
    
}